package com.ajie.utils;

import cn.hutool.core.util.RandomUtil;
import com.ajie.model.Result;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Paths;
import java.util.UUID;

/**
 * @author: ajie
 * @createTime: 2024-08-11 15:12
 */
public class FileUtils {

    public static final String path = "/uploads/image/";

    public static String upload(MultipartFile file) {
        if (file.isEmpty()) {
            throw new RuntimeException("上传文件不能为空！");
        }
        try {
            createDir(path);
            if (file.getOriginalFilename() != null) {
                String filename = filename(file.getOriginalFilename());
                // 使用原始文件名保存文件
                String filePath = path + filename;
                file.transferTo(Paths.get(filePath));
                return filename;
            }
        } catch (IOException e) {
        }
        return null;
    }

    /**
     * 创建文件夹
     * @param path
     */
    private static void createDir(String path) {
        // 保存文件到本地系统，这里假设我们保存到"uploads"目录
        File directory = new File(path);
        if (!directory.exists()) {
            directory.mkdirs();
        }
    }

    /**
     * 根据文件名生成时间文件名
     * @param fileName
     * @return
     */
    public static String filename(String fileName){
        // 规则 1、UUID重复几率很小(UUID.randomUUID())；2、时间戳重复几率0，但是会有多线程问题(System.currentTimeMillis())
        return RandomUtil.randomString(32) + fileName.substring(fileName.lastIndexOf("."));
    }

}
